package com.hxd.otc.module.fiat_deal.fragment;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.api.Constant;
import com.hxd.otc.base.LazyFragment;
import com.hxd.otc.base.OnMultiClickListener;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.dialog.ForbiddenBankCardDialog;
import com.hxd.otc.module.fiat_deal.contract.DealContract;
import com.hxd.otc.module.fiat_deal.presenter.DealPresenter;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.my.activity.AccountInfoActivity;
import com.hxd.otc.module.my.activity.PublishAdvertisementActivity;
import com.hxd.otc.utils.StatusBarHelper;
import com.hxd.otc.utils.UIUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lzy on 2018/9/15 0015.
 * description ${交易Fragment}
 */
public class DealFragment extends LazyFragment<DealPresenter> implements DealContract.IView, TabHost.OnTabChangeListener, View.OnClickListener {

    @BindView(android.R.id.tabhost)
    FragmentTabHost mTabHost;
    @BindView(R.id.ll_error)
    View mLlError;
    @BindView(R.id.tv_refresh)
    View mTvRefresh;
    @BindView(R.id.iv_add)
    ImageView mIvAdd;

    private ForbiddenBankCardDialog<String> mSetNickNameDialog;
    private DealFilterDialogFragment mFilterDialogFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_deal;
    }

    @Override
    protected DealPresenter createPresenter() {
        return new DealPresenter(this);
    }

    @Override
    protected void initView() {
        mLlError.setVisibility(View.GONE);
        mPresenter.getDealTeam();
    }

    @Override
    public void gainDealTeamSuccess() {
        initFragmentTabHost();
        mLlError.setVisibility(View.GONE);
        mTvRefresh.setOnClickListener(this);
    }

    @Override
    public void gainDealTeamFail(String errMessage) {
        showToast(errMessage);
        mLlError.setVisibility(View.VISIBLE);
        mTvRefresh.setOnClickListener(this);
    }

    private void initFragmentTabHost() {
        String[] titles = getResources().getStringArray(R.array.deal_type_titles);
        Class[] fragments = new Class[]{SubDealFragment.class, SubDealFragment.class};
        mTabHost.setup(getContext(), getChildFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
        for (int i = 0; i < titles.length; i++) {
            View indicatorView = View.inflate(getContext(), R.layout.tab_indicator_of_deal, null);
            TextView tvTitle = indicatorView.findViewById(R.id.tv_title);
            tvTitle.setText(titles[i]);
            tvTitle.setBackgroundResource(i == 0 ? R.drawable.selector_deal_tab_left : R.drawable.selector_deal_tab_right);
            Bundle bundle = new Bundle();
            bundle.putInt(DealListFragment.EXTRA_DEAL_TYPE, i == 0 ? Constant.Deal.TYPE_BUY : Constant.Deal.TYPE_SELL);
            bundle.putSerializable(SubDealFragment.EXTRA_ALL_DEAL_TEAM_BEANS, mPresenter.getAllDealTeamBeans());
            mTabHost.addTab(
                    mTabHost.newTabSpec(titles[i]).setIndicator(indicatorView), fragments[i], bundle);
        }
        mTabHost.setOnTabChangedListener(this);
        mTabHost.setCurrentTab(0);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            FragmentTabHost.LayoutParams layoutParams = (FragmentTabHost.LayoutParams) mLlError.getLayoutParams();
            layoutParams.topMargin = layoutParams.topMargin + StatusBarHelper.getStatusBarHeight(getContext());
            mLlError.setLayoutParams(layoutParams);
        }
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initEvent() {
        mIvAdd.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                onPublishAdvert();
            }
        });
    }

    @Override
    public void onTabChanged(String tabId) {
    }

    @OnClick({R.id.tv_fiats, R.id.tv_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_fiats:
                onFilter();
                break;
            case R.id.tv_refresh:
                mTvRefresh.setOnClickListener(null);
                mPresenter.getDealTeam();
                break;
        }
    }

    /**
     * 打开筛选对话框
     */
    private void onFilter() {
        ArrayList<String> fiats = mPresenter.getFiats();
        if (fiats == null || fiats.size() == 0) {
            showToast(getString(R.string.failed_to_obtain_legal_currency_information_please_try_again_later));
            return;
        }
        if (mFilterDialogFragment == null) {
            mFilterDialogFragment = DealFilterDialogFragment.getInstance(fiats)
                    .setOnConfirmListener(new DealFilterDialogFragment.OnConfirmListener() {
                        @Override
                        public void onConfirm(String fiat, String bankTypeValue) {
                            updateFilterConditions(fiat, bankTypeValue);
                        }
                    });
        }
        mFilterDialogFragment
                .setCurFiat(getFiat())
                .setCurBankTypeValue(getBankTypeValue())
                .showAllowingStateLoss(getChildFragmentManager(), DealFilterDialogFragment.class.getSimpleName());
    }

    private void onPublishAdvert() {
        if (!UserHelper.isLogin()) {
            $startActivity(LoginActivity.class);
            return;
        }

        if (!UserHelper.isSilver()) {
            showToast(getString(R.string.you_are_not_silver_permission));
            return;
        }

        if (TextUtils.isEmpty(UserHelper.getNickName())) {
            showSetNickNameDialog();
            return;
        }
        $startActivity(PublishAdvertisementActivity.class);
    }

    /**
     * 提示设置昵称对话框
     */
    private void showSetNickNameDialog() {
        if (mSetNickNameDialog == null) {
            mSetNickNameDialog = new ForbiddenBankCardDialog<String>(getContext())
                    .setMessage(getString(R.string.advertiser_hangs_a_bill_before_must_set_nickname_first))
                    .setOnConfirmClickListener(new ForbiddenBankCardDialog.OnConfirmClickListener<String>() {
                        @Override
                        public void onConfirm(String data) {
                            $startActivity(AccountInfoActivity.class);
                        }
                    });
        }
        mSetNickNameDialog.show();
    }

    public String getFiat() {
        return mPresenter.getFiat();
    }

    public String getBankTypeValue() {
        return mPresenter.getBankTypeValue();
    }

    public void updateFilterConditions(String fiat, String bankTypeValue) {
        //条件与之前一致，不需重新请求数据
        if (getFiat().equals(fiat) && getBankTypeValue().equals(bankTypeValue)) return;
        //更新筛选条件
        mPresenter.setFiat(fiat);
        mPresenter.setBankTypeValue(bankTypeValue);

        //筛选条件更新后，通知当前显示的子页面进行重新请求
        for (Fragment fragment : getChildFragmentManager().getFragments()) {
            if (fragment instanceof SubDealFragment && fragment.isAdded() && fragment.getUserVisibleHint()) {
                ((SubDealFragment) fragment).updateFilterConditions();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UIUtils.dismissDialog(mSetNickNameDialog);
    }
}
